<?php

namespace App\Admin\Controllers;

use App\Http\Traits\GlobalConstant;
use App\Models\Course;
use App\Models\CourseSection;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Support\Facades\Log;

class CourseSectionController extends BaseController
{

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('课程章节列表')
            ->description(' ')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('课程章节详情')
            ->description(' ')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('编辑课程章节')
            ->description(' ')
            ->body($this->form($id)->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('新增课程章节')
            ->description('新增课程章节')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new CourseSection());
        $grid->filter(function ($filter) {
            // 去掉默认的id过滤器
            $filter->disableIdFilter();

            $filter->column(1 / 2, function ($filter) {
                $filter->like('name', '章节名称');
                $filter->equal('courseInfo.id', '课程')->select(Course::where('valid', 1)->pluck('name as text', 'id'));
            });
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('status', '状态')->select(['禁用', '正常']);
//                $filter->between('class_timed','上课时间')->date();
                $filter->where(function ($query) {
                    $startTime = strtotime($this->input . ' 00:00:00');
                    $endTime   = strtotime($this->input . ' 23:59:59');
                    $query->where('class_time', '>=', $startTime)->where('class_time', '<=', $endTime);
                }, '上课时间', 'class_time')->date();
            });

        });
//
        $grid->model()->orderBy('status', 'desc');
        $grid->column('id', '#');
        $grid->column('serial_number', '章节序号')->sortable();
        $grid->column('name', '章节名称');
        $grid->column('courseInfo.name', '所属课程');
        $grid->column('class_time', '上课时间');
        $grid->column('aa', '具体时间')->display(function () {
            return $this->begin_time . '-' . $this->end_time;
        });
        $grid->column('status', __('状态'))->display(function ($v) {
            return GlobalConstant::_STATUS[$v];
        })->label([0 => 'danger', 1 => 'success'])->sortable();
        $grid->column('created_at', __('created_at'))->sortable();
        $grid->column('updated_at', __('updated_at'));

        $grid->actions(function ($actions) {
            $actions->disableDelete();
            $actions->disableView();

        });
        $grid->disableRowSelector();
        $grid->tools(function ($tools) {
            $tools->batch(function ($batch) {
                $batch->disableDelete();
            });
        });
        $grid->expandFilter();
        Admin::style('.img-thumbnail {width: 60px;height:60px}');
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(CourseSection::findOrFail($id));

        $show->panel()
            ->tools(function ($tools) {
                $tools->disableDelete();
            });
        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($id = 0)
    {
        $courseId = request('c_id') ?? 0;
        $form     = new Form(new CourseSection());
        if (!empty($id)) {
            $courseId = CourseSection::where('id', $id)->value('course_id');
        }
        $form->hidden('id', 'id');
        if (empty($courseId)) {
            $form->select('course_id', '课程')->options(Course::where('valid', 1)->pluck('name as text', 'id'))->required();
        } else {
            $form->hidden('course_id', '课程')->default($courseId);
        }
        $form->text('name', '章节名称')->required()->attribute(['autocomplete' => 'off']);
        $form->number('serial_number', '章节序号')->required()->min(1)->default(1);

        $form->date('class_time', '上课时间')->required();
        $form->time('begin_time', '具体开始时间')->format('HH:mm')->required();
        $form->time('end_time', '具体结束时间')->format('HH:mm')->required();
        $form->radio('status', '状态')->options(GlobalConstant::_STATUS)->default(1);
        $form->tools(function (Form\Tools $tools) use ($courseId) {
            // 去掉`删除`按钮
            $tools->disableDelete();
            $tools->disableView();
            $tools->disableList();
            $url  = '/admin/course-edit?c_id=' . $courseId;
            $html = <<<HTML
<div class="btn-group pull-right grid-create-btn" style="margin-right: 10px">
    <a href="$url" class="btn btn-sm btn-success">
        <i class="fa fa-bars"></i>&nbsp;&nbsp;返回课程详情
    </a>
</div>
HTML;
            $tools->add($html);
        });
        if ($id == 0) {
            $form->setAction('/admin/course-section/save');
        } else {
            $form->setAction('/admin/course-section/update');
        }

        $form->footer(function ($footer) {
            // 去掉`查看`checkbox
            $footer->disableViewCheck();
            // 去掉`继续编辑`checkbox
            $footer->disableEditingCheck();
            // 去掉`继续创建`checkbox
            $footer->disableCreatingCheck();
            $footer->disableReset();
        });
        return $form;
    }

    public function store()
    {
        $param = request()->input();
        $info  = CourseSection::where('course_id', $param['course_id'])->where('serial_number', $param['serial_number'])->first();
        if ($info) {
            Log::error('章节已存在1');
            admin_error('当前章节"' . $param['serial_number'] . '"在当前课程已经存在');
            return back();
        }
        unset($param['_token']);
        unset($param['_previous_']);
        unset($param['s']);
        CourseSection::create($param);
        return redirect('admin/course-edit?c_id=' . $param['course_id']);
    }

    public function update($id)
    {
        $param = request()->input();
        $info  = CourseSection::where('course_id', $param['course_id'])->where('serial_number', $param['serial_number'])->where('id', '!=', $param['id'])->first();
        if ($info) {
            Log::error('章节已存在2');
            admin_error('当前章节"' . $param['serial_number'] . '"在当前课程已经存在');
            return back();
        }
        try {
            unset($param['_token']);
            unset($param['_method']);
            unset($param['_previous_']);
            unset($param['s']);
            $detail = CourseSection::where('id', $param['id'])->first();
            $detail->fill($param);
            $detail->save();
            admin_success("操作成功");
            return redirect('admin/course-edit?c_id=' . $param['course_id']);
        } catch (\Exception $exception) {
            admin_error("操作失败,原因" . $exception->getMessage());
            return back();
        }
    }

}
